package com.apicloud.modulehttp;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpClient {

    public static class Response {
        public int code;
        public JSONObject headers = new JSONObject();
        public String body;

        public Response(int code, Map<String, List<String>> headers, String body) throws JSONException {
            this.code = code;
            if(headers!=null) {
                for ( Map.Entry<String, List<String>> entry : headers.entrySet() ) {
                    String key = entry.getKey();
                    if(key==null) continue;
                    String value = "";
                    List<String> arr = entry.getValue();
                    for (int i = 0, size = arr.size(); i < size; i++) {
                        if(i>0) value += ",";
                        value += arr.get(i);
                    }
                    this.headers.put(key, value);
                }
            }
            this.body = body;
        }
    }

    private String charset = "utf-8";
    private int timeout = 30000;

    public HttpClient(String charset, int timeout){
        this.charset = charset;
        this.timeout = timeout;
    }
    //从流中读取数据
    private byte[] streamToBytes(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer,0,len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    //get
    public Response get(String path, JSONObject headers) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(timeout);
        conn.setRequestMethod("GET");
        //请求头
        if(headers!=null) {
            Iterator it = headers.keys();
            while (it.hasNext()){
                String key = (String) it.next();
                conn.addRequestProperty(key, headers.getString(key));
            }
        }
        //响应内容
        InputStream in = conn.getInputStream();
        byte[] indata = streamToBytes(in);
        String body = new String(indata, charset);
        //响应头
        Map<String, List<String>> responseHeaders = conn.getHeaderFields();

        return new Response(conn.getResponseCode(), responseHeaders ,body);
    }
    public Response get(String path) throws Exception {
        return get(path, null);
    }
    //post
    public Response post(String path, JSONObject data, JSONObject headers) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);
        conn.setRequestMethod("POST");
        //请求头
        if(headers!=null) {
            Iterator it = headers.keys();
            while (it.hasNext()){
                String key = (String) it.next();
                conn.addRequestProperty(key, headers.getString(key));
            }
        }
        //设置运行输入,输出:
        conn.setDoOutput(true);
        conn.setDoInput(true);
        //Post方式不能缓存,需手动设置为false
        conn.setUseCaches(false);
        //发送数据
        if(data!=null){
            String postData = "";
            Iterator it = data.keys();
            while (it.hasNext()){
                String key = (String) it.next();
                postData += key+"="+ URLEncoder.encode(data.getString(key), "UTF-8")+"&";
            }
            postData = postData.substring(0, postData.length()-1);
            OutputStream out = conn.getOutputStream();
            out.write(postData.getBytes());
            out.flush();
        }
        //响应内容
        InputStream in = conn.getInputStream();
        byte[] indata = streamToBytes(in);
        String body = new String(indata, charset);
        //响应头
        Map<String, List<String>> responseHeaders = conn.getHeaderFields();

        return new Response(conn.getResponseCode(), responseHeaders ,body);
    }
    public Response post(String path, JSONObject data) throws Exception {
        return post(path, data, null);
    }
}
